package com.jianggy.jdbc.xa;

import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;

import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.sql.Connection;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;

/**
 * @author jianggy
 * @version 1.0
 * @time 2019/12/9 17:35
 * @see
 **/
public class XaDemo {
    public static MysqlXADataSource getDataSource(String url,String user,String psw){
        try {
            MysqlXADataSource ds = new MysqlXADataSource();
            ds.setURL(url);
            ds.setUser(user);
            ds.setPassword(psw);
            return ds;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args){
        String url1 = "jdbc:mysql://39.105.162.92:3389/test";
        String username1 = "root";
        String psw1 = "1qaz!QAZ";
        String url2 = "jdbc:mysql://39.105.162.92:3389/test1";
        String username2 = "root";
        String psw2 = "1qaz!QAZ";
        Xid xid1 = null;
        Xid xid2 = null;
        XAResource resource1 = null;
        XAResource resource2 = null;

        try {
            MysqlXADataSource ds1 = getDataSource(url1,username1,psw1);
            MysqlXADataSource ds2 = getDataSource(url2,username2,psw2);

            XAConnection xaConnection1 = ds1.getXAConnection();
             resource1 = xaConnection1.getXAResource();
            Connection connection1 = xaConnection1.getConnection();
            Statement statement1 = connection1.createStatement();

            XAConnection xaConnection2 = ds2.getXAConnection();
             resource2 = xaConnection2.getXAResource();
            Connection connection2 = xaConnection2.getConnection();
            Statement statement2 = connection2.createStatement();

             xid1 = new MyXid(100,new byte[]{0X01},new  byte[]{0x02});
             xid2 = new MyXid(100,new byte[]{0x11},new byte[]{0x12});

            resource1.start(xid1,XAResource.TMNOFLAGS);
            statement1.execute("update  test set height=1 where  id=1");
            resource1.end(xid1,XAResource.TMSUCCESS);

            resource2.start(xid2,XAResource.TMNOFLAGS);
            statement2.execute("update  test set height=2 where  id=1");
            resource2.end(xid2,XAResource.TMSUCCESS);

            TimeUnit.SECONDS.sleep(30);
            int ret1 = resource1.prepare(xid1);
            int ret2 = resource2.prepare(xid2);

            if (ret1 == XAResource.XA_OK&& ret2 == XAResource.XA_OK){
                resource1.commit(xid1,false);
                resource2.commit(xid2,false);
            }
        }catch (Exception e){
          try {
              resource1.rollback(xid1);
              resource2.rollback(xid2);
          }catch (Exception e1){
              e1.printStackTrace();
          }
            e.printStackTrace();
        }
    }
}
